# ui/qt6_summary_window.py
# -*- coding: utf-8 -*-
"""
Qt6 今日汇总窗口 - 只读表格 + 导出Excel + 刷新按钮
"""
import sys, os, csv, datetime
from pathlib import Path
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget,
    QPushButton, QComboBox, QLabel, QHBoxLayout, QFileDialog, QMessageBox
)
from PyQt6.QtCore import Qt, QSortFilterProxyModel
from PyQt6.QtGui import QStandardItemModel, QStandardItem

from utils.logger import log


class SummaryWindow(QMainWindow):
    def __init__(self, csv_path):
        super().__init__()
        self.csv_path = csv_path
        self.setWindowTitle("今日汇总 - Qt6表格预览")
        self.resize(900, 500)

        # 设置窗口属性，避免关闭时影响主程序
        self.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)  # 重要！
        self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)

        # 立即初始化UI
        self.init_ui()
        self.load_csv()

    def closeEvent(self, event):
        """重写关闭事件，只关闭本窗口"""
        print("[DEBUG] 汇总窗口关闭")
        event.accept()  # 接受关闭，只关闭本窗口

    def init_ui(self):
        """初始化UI"""
        central = QWidget()
        self.setCentralWidget(central)
        layout = QVBoxLayout(central)
        
        # 顶部筛选栏
        top_layout = QHBoxLayout()
        top_layout.addWidget(QLabel("状态筛选:"))
        self.filter_box = QComboBox()
        self.filter_box.addItem("全部")
        self.filter_box.currentTextChanged.connect(self.apply_filter)
        top_layout.addWidget(self.filter_box)
        top_layout.addStretch()
        
        # ★★★ 新增：刷新按钮
        self.refresh_btn = QPushButton("🔄 刷新")
        self.refresh_btn.clicked.connect(self.refresh_data)
        self.refresh_btn.setToolTip("刷新表格数据")
        top_layout.addWidget(self.refresh_btn)
        
        self.export_btn = QPushButton("📊 导出Excel")
        self.export_btn.clicked.connect(self.export_excel)
        top_layout.addWidget(self.export_btn)
        
        layout.addLayout(top_layout)
        
        # 表格
        self.table = QTableView()
        layout.addWidget(self.table)
        
        # 空壳模型（防崩溃）
        self.proxy = QSortFilterProxyModel()
        self.table.setModel(self.proxy)
        
        # 底部总时长
        self.total_label = QLabel("总时长: 0秒")
        layout.addWidget(self.total_label)

    def refresh_data(self):
        """刷新表格数据 - 纯只读刷新"""
        try:
            log('手动刷新汇总')
            
            # 直接重新加载数据（只读模式不会影响主程序）
            self.load_csv()
            
            # 显示成功消息
            self.statusBar().showMessage("数据已刷新", 2000)
            log('已刷新')
            
        except Exception as e:
            log(f'[ERR] 刷新汇总表格失败: {e}')
            self.statusBar().showMessage(f"刷新失败: {e}", 3000)
            QMessageBox.critical(self, "刷新失败", f"刷新数据失败:\n{e}")

    def load_csv(self):
        """加载CSV数据 - 纯只读模式"""
        if not self.csv_path.exists():
            QMessageBox.information(self, "无数据", "今天还没有记录。")
            return

        # 读取CSV - 纯只读模式
        rows = []
        # 标准的只读模式，不会影响其他程序写入
        with open(self.csv_path, 'r', encoding='utf-8-sig', newline='') as f:
            reader = csv.reader(f)
            header = next(reader)
            for row in reader:
                if len(row) >= 8:
                    rows.append(row) 

        # 按照开始时间排序（最新的在最上面）
        def sort_key(row):
            if len(row) >= 6:
                try:
                    # 组合日期和时间进行排序
                    date_str = row[0]  # 日期
                    time_str = row[5]  # 开始时间
                    return datetime.datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M:%S")
                except:
                    return datetime.datetime.min
            return datetime.datetime.min
        
        # 按时间降序排列（最新的在最上面）
        rows.sort(key=sort_key, reverse=True)

        # 填充表格模型
        self.model = QStandardItemModel(len(rows), len(header))
        self.model.setHorizontalHeaderLabels(header)

        state_set = set()
        total_secs = 0

        for r, row in enumerate(rows):
            for c, val in enumerate(row[:len(header)]):
                item = QStandardItem(val)
                item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)
                self.model.setItem(r, c, item)

            # 收集状态
            state_set.add(row[4])
            # 累加时长（第8列）
            try:
                total_secs += int(row[7])
            except:
                pass

        # 填充筛选下拉框
        self.filter_box.clear()
        self.filter_box.addItem("全部")
        for s in sorted(state_set):
            self.filter_box.addItem(s)

        # 排序代理模型
        self.proxy = QSortFilterProxyModel()
        self.proxy.setSourceModel(self.model)
        self.table.setModel(self.proxy)

        # 显示总时长
        self.total_label.setText(f"总时长: {self.format_duration(total_secs)}")
        
        # 自动选中第一行（最新记录）
        if rows:
            self.table.selectRow(0)

    def apply_filter(self, text):
        if text == "全部":
            self.proxy.setFilterFixedString("")
        else:
            self.proxy.setFilterKeyColumn(4)  # 第5列是状态
            self.proxy.setFilterFixedString(text)

    def export_excel(self):
        """真 · 导出 xlsx，带列宽、自动筛选"""
        from openpyxl import Workbook
        from openpyxl.utils import get_column_letter
        import os

        default_name = f"{self.csv_path.stem}.xlsx"
        path, _ = QFileDialog.getSaveFileName(self, "保存Excel", default_name, "Excel Files (*.xlsx)")
        if not path:
            return

        try:
            wb = Workbook()
            ws = wb.active
            ws.title = "今日汇总"

            # 1. 写表头
            header = [self.model.headerData(i, Qt.Orientation.Horizontal) for i in range(self.model.columnCount())]
            ws.append(header)

            # 2. 写数据
            for r in range(self.model.rowCount()):
                row = [self.model.index(r, c).data() for c in range(self.model.columnCount())]
                ws.append(row)

            # 3. 简单美化：自动列宽 + 自动筛选
            for col in range(1, len(header) + 1):
                ws.column_dimensions[get_column_letter(col)].auto_size = True
            ws.auto_filter.ref = ws.dimensions

            wb.save(path)
            QMessageBox.information(self, "完成", f"已导出真 · Excel:\n{path}")
        except Exception as e:
            QMessageBox.critical(self, "失败", f"导出失败:\n{e}")

    @staticmethod
    def format_duration(seconds):
        h, s = divmod(seconds, 3600)
        m, s = divmod(s, 60)
        return f"{h}小时{m}分{s}秒"


def show_summary_window(data_dir: str, user_id: str):
    """外部唯一入口：返回窗口实例以保持引用"""
    from PyQt6.QtWidgets import QApplication, QMessageBox
    from PyQt6.QtCore import Qt
    import datetime
    from pathlib import Path

    today = datetime.date.today().strftime("%Y-%m-%d")
    csv_path = Path(data_dir) / "logs" / f"{today}_{user_id}.csv"

    # 今天没文件就提示
    if not csv_path.exists():
        QMessageBox.information(None, "无数据", "今天还没有记录。")
        return None

    try:
        # 创建并显示窗口
        window = SummaryWindow(csv_path)
        
        # 设置窗口标志，确保是独立窗口
        window.setWindowFlags(Qt.WindowType.Window)
        window.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
        window.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)
        
        window.show()
        window.raise_()
        window.activateWindow()
        
        # 返回窗口实例以保持引用
        return window
        
    except Exception as e:
        print(f"[ERR] 打开汇总窗口失败: {e}")
        QMessageBox.critical(None, "错误", f"打开汇总窗口失败:\n{e}")
        return None


if __name__ == "__main__":
    # 调试模式
    import sys
    print("[DEBUG] 开始单独测试汇总窗口...")
    
    # 如果提供了参数，使用参数
    if len(sys.argv) == 3:
        data_dir = sys.argv[1]
        user_id = sys.argv[2]
        print(f"[DEBUG] 使用参数: data_dir={data_dir}, user_id={user_id}")
    else:
        # 使用默认值测试
        data_dir = "D:\\python_Data"
        user_id = "admin-csp"
        print(f"[DEBUG] 使用默认值: data_dir={data_dir}, user_id={user_id}")
    
    try:
        app = QApplication(sys.argv)
        print("[DEBUG] QApplication 创建成功")
        
        # 创建并显示窗口
        today = datetime.date.today().strftime("%Y-%m-%d")
        csv_path = Path(data_dir) / "logs" / f"{today}_{user_id}.csv"
        print(f"[DEBUG] CSV路径: {csv_path}")
        
        if not csv_path.exists():
            print("[DEBUG] CSV文件不存在，创建测试文件...")
            # 创建测试文件
            csv_path.parent.mkdir(parents=True, exist_ok=True)
            with open(csv_path, 'w', encoding='utf-8-sig') as f:
                f.write('日期,工号,角色,作业/非作业,状态,开始,结束,时长(秒),主被动切换,项目名称,作业类型,任务ID,工作量1,工作量2,工作量3,备注\n')
                f.write('2025-11-19,admin-csp,管理员,作业,作业(数据更新),14:00:00,14:30:00,1800,手动,测试项目,数据更新,123,100,,,测试备注\n')
        
        # 直接创建窗口实例
        window = SummaryWindow(csv_path)
        window.show()
        print("[DEBUG] 窗口显示成功")
        
        print("[DEBUG] 进入事件循环...")
        sys.exit(app.exec())
        
    except Exception as e:
        print(f"[DEBUG] 发生异常: {e}")
        import traceback
        traceback.print_exc()
        input("按回车键退出...")